<template>
  <el-card shadow="never" style="margin-top: 8px" body-style="padding:0px;" class="my-fill">
    <template #header>
      <el-input v-model="state.filterText" placeholder="筛选型号" clearable />
    </template>
    <el-scrollbar v-loading="state.loading" height="100%" max-height="100%" :always="false" wrap-style="padding:10px">
      <el-tree ref="orgMenuRef" :data="state.PLCDeviceData" node-key="id" :props="{ label: 'model' }"
        :filter-node-method="onFilterNode" highlight-current check-strictly default-expand-all render-after-expand
        :expand-on-click-node="false" v-bind="$attrs" @node-click="onNodeClick" @check-change="onCheckChange" />
    </el-scrollbar>
  </el-card>
</template>

<script lang="ts" setup name="industry/plc-device/menu">
import { onMounted, reactive, ref, watch, nextTick, PropType } from 'vue'
import { PLCDeviceGetListOutput } from '/@/api/industry/data-contracts'
import { PlcDeviceApi } from '/@/api/industry/PlcDevice'
import { listToTree } from '/@/utils/tree'
import { ElTree } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Array as PropType<number[] | undefined | null>,
    default: () => [],
  },
  selectFirstNode: {
    type: Boolean,
    default: () => false,
  },
})

const PLCDeviceMenuRef = ref<InstanceType<typeof ElTree>>()
const state = reactive({
  loading: false,
  filterText: '',
  PLCDeviceData: [] as Array<PLCDeviceGetListOutput>,
  lastKey: 0,
})

watch(
  () => state.filterText,
  (val) => {
    PLCDeviceMenuRef.value?.filter(val)
  }
)

onMounted(() => {
  initData()
})

const emits = defineEmits<{
  (e: 'node-click', node: PLCDeviceGetListOutput | null): void
  (e: 'update:modelValue', node: any[] | undefined | null): void
}>()

const onFilterNode = (value: string, data: PLCDeviceGetListOutput) => {
  if (!value) return true
  return data.model?.indexOf(value) !== -1
}

const onNodeClick = (node: PLCDeviceGetListOutput) => {
  if (state.lastKey === node.id) {
    state.lastKey = 0
    PLCDeviceMenuRef.value?.setCurrentKey(undefined)
    emits('node-click', null)
  } else {
    state.lastKey = node.id as number
    emits('node-click', node)
  }
}

const onCheckChange = () => {
  emits('update:modelValue', PLCDeviceMenuRef.value?.getCheckedKeys())
}

const initData = async () => {
  state.loading = true
  const res = await new PlcDeviceApi().getList({ lineCode: '', lineName: '' }).catch(() => {
    state.loading = false
  })
  state.loading = false
  if (res?.success && res.data && res.data.length > 0) {
    state.PLCDeviceData = listToTree(res.data)
    if (state.PLCDeviceData.length > 0 && props.selectFirstNode) {
      nextTick(() => {
        const firstNode = state.PLCDeviceData[0]
        PLCDeviceMenuRef.value?.setCurrentKey(firstNode.id)
        onNodeClick(firstNode)
      })
    }
  } else {
    state.PLCDeviceData = []
  }
}

defineExpose({
  PLCDeviceMenuRef,
})
</script>
